const crypto = require("crypto");
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const algorithm = "aes-256-cbc"; //使用 AES 加密

exports.md5 = (content) => {
  const _md5 = crypto.createHash("md5");
  return _md5.update(content).digest("hex");
};

/**
 * 加密文本
 * @param {string | object} text
 * @returns
 */
exports.encrypt = (text) => {
  if (typeof text !== "string") {
    text = JSON.stringify(text);
  }
  let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
  let encrypted = cipher.update(text);
  encrypted = Buffer.concat([encrypted, cipher.final()]);
  return encrypted.toString("hex");
};

/**
 * 解密文本
 * @param {string} text
 * @returns
 */
exports.decrypt = (text) => {
  let encryptedText = Buffer.from(text, "hex");
  let decipher = crypto.createDecipheriv(
    algorithm,
    Buffer.from(key),
    Buffer.from(iv, "hex")
  );
  let decrypted = decipher.update(encryptedText);
  decrypted = Buffer.concat([decrypted, decipher.final()]);
  let content = decrypted.toString();
  try {
    content = JSON.parse(content);
  } catch (error) {
    console.log("error:", error);
  }
  return content;
};
